<template>
  <div class="caregiver-medicine-receive-container">
    <div class="header">
      <h2>药品领用</h2>
      <p>记录和管理药品领用信息</p>
    </div>

    <!-- 药品领用表单 -->
    <div class="form-section">
      <el-card shadow="never" class="form-card">
        <template #header>
          <div class="card-header">
            <span>药品领用记录</span>
          </div>
        </template>
        <el-form :model="receiveForm" :rules="receiveRules" ref="receiveFormRef" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="选择老人" prop="elderId">
                <el-select
                  v-model="receiveForm.elderId"
                  placeholder="请选择老人"
                  filterable
                  style="width: 100%"
                  @change="handleElderChange"
                >
                  <el-option
                    v-for="elder in elderList"
                    :key="elder.elderId"
                    :label="elder.name"
                    :value="elder.elderId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择药品" prop="medicineId">
                <el-select
                  v-model="receiveForm.medicineId"
                  placeholder="请选择药品"
                  filterable
                  style="width: 100%"
                  @change="handleMedicineChange"
                >
                  <el-option
                    v-for="medicine in medicineList"
                    :key="medicine.medicineId"
                    :label="medicine.medicineName"
                    :value="medicine.medicineId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用法用量" prop="dosageUsed">
                <el-input
                  v-model="receiveForm.dosageUsed"
                  placeholder="请输入用法用量"
                  :readonly="true"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="领用时间" prop="receiveTime">
                <el-date-picker
                  v-model="receiveForm.receiveTime"
                  type="datetime"
                  placeholder="选择领用时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注说明" prop="notes">
            <el-input
              v-model="receiveForm.notes"
              type="textarea"
              :rows="3"
              placeholder="请输入备注说明（可选）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              <el-icon><DocumentAdd /></el-icon>
              提交领用记录
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 最近领用记录 -->
    <div class="recent-records-section">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>最近领用记录</span>
            <el-button type="primary" link @click="loadRecentRecords">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>

        <el-table
          :data="recentRecords"
          v-loading="recordsLoading"
          style="width: 100%"
          :default-sort="{ prop: 'receiveTime', order: 'descending' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="elderName" label="老人姓名" width="120" align="center" />
          <el-table-column prop="medicineName" label="药品名称" width="150" align="center" />
          <el-table-column prop="dosageUsed" label="用法用量" width="150" align="center" />
          <el-table-column prop="receiveTime" label="领用时间" width="180" align="center" sortable>
            <template #default="{ row }">
              {{ formatDateTime(row.receiveTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="notes" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="recordsPagination.currentPage"
            v-model:page-size="recordsPagination.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="recordsPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleRecordsSizeChange"
            @current-change="handleRecordsCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentAdd, Refresh } from '@element-plus/icons-vue'
import { getMyElders } from '@/api/elder'
import { getMedicines, addMedicineReceiveRecord, getMedicineReceiveRecords } from '@/api/medicine'

// 药品领用表单
const receiveFormRef = ref()
const receiveForm = reactive({
  elderId: '',
  medicineId: '',
  dosageUsed: '',
  receiveTime: '',
  notes: ''
})

// 表单验证规则
const receiveRules = {
  elderId: [
    { required: true, message: '请选择老人', trigger: 'change' }
  ],
  medicineId: [
    { required: true, message: '请选择药品', trigger: 'change' }
  ],
  dosageUsed: [
    { required: true, message: '请输入用法用量', trigger: 'blur' }
  ],
  receiveTime: [
    { required: true, message: '请选择领用时间', trigger: 'change' }
  ]
}

// 数据列表
const elderList = ref([])
const medicineList = ref([])
const recentRecords = ref([])

// 加载状态
const submitting = ref(false)
const recordsLoading = ref(false)

// 分页配置
const recordsPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 状态映射
const statusMap = {
  'completed': { text: '已完成', type: 'success' },
  'pending': { text: '待处理', type: 'warning' },
  'cancelled': { text: '已取消', type: 'info' }
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status]?.text || status
}

// 获取状态类型
const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 老人选择变化
const handleElderChange = (elderId) => {
  const elder = elderList.value.find(item => item.elderId === elderId)
  if (elder) {
    console.log('选择老人:', elder.name)
  }
}

// 药品选择变化
const handleMedicineChange = (medicineId) => {
  const medicine = medicineList.value.find(item => item.medicineId === medicineId)
  if (medicine) {
    // 自动填充用法用量
    receiveForm.dosageUsed = medicine.usageMethod || ''
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!receiveFormRef.value) return

  try {
    const valid = await receiveFormRef.value.validate()
    if (!valid) return

    submitting.value = true

    // 设置当前时间为默认领用时间
    if (!receiveForm.receiveTime) {
      receiveForm.receiveTime = new Date().toISOString().replace('T', ' ').substring(0, 19)
    }

    const response = await addMedicineReceiveRecord(receiveForm)
    if (response.code === 200) {
      ElMessage.success('药品领用记录提交成功')
      handleReset()
      // 刷新最近领用记录
      loadRecentRecords()
    } else {
      ElMessage.error(response.msg || '提交失败')
    }
  } catch (error) {
    console.error('提交药品领用记录失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const handleReset = () => {
  receiveFormRef.value?.resetFields()
  Object.assign(receiveForm, {
    elderId: '',
    medicineId: '',
    dosageUsed: '',
    receiveTime: '',
    notes: ''
  })
}

// 加载老人列表
const loadElderList = async () => {
  try {
    const response = await getMyElders()
    if (response.code === 200) {
      elderList.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取老人列表失败')
      // 模拟数据
      elderList.value = [
        { elderId: 1, name: '张大爷' },
        { elderId: 2, name: '李大妈' },
        { elderId: 3, name: '王爷爷' }
      ]
    }
  } catch (error) {
    console.error('获取老人列表失败:', error)
    // 模拟数据
    elderList.value = [
      { elderId: 1, name: '张大爷' },
      { elderId: 2, name: '李大妈' },
      { elderId: 3, name: '王爷爷' }
    ]
  }
}

// 加载药品列表
const loadMedicineList = async () => {
  try {
    const response = await getMedicines()
    if (response.code === 200) {
      medicineList.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取药品列表失败')
      // 模拟数据
      medicineList.value = [
        {
          medicineId: 1,
          medicineName: '降压药',
          usageMethod: '口服，每日一次，每次一片',
          specification: '10mg*30片'
        },
        {
          medicineId: 2,
          medicineName: '降糖药',
          usageMethod: '口服，每日两次，每次一片',
          specification: '5mg*60片'
        },
        {
          medicineId: 3,
          medicineName: '钙片',
          usageMethod: '口服，每日一次，每次两片',
          specification: '500mg*100片'
        }
      ]
    }
  } catch (error) {
    console.error('获取药品列表失败:', error)
    // 模拟数据
    medicineList.value = [
      {
        medicineId: 1,
        medicineName: '降压药',
        usageMethod: '口服，每日一次，每次一片',
        specification: '10mg*30片'
      },
      {
        medicineId: 2,
        medicineName: '降糖药',
        usageMethod: '口服，每日两次，每次一片',
        specification: '5mg*60片'
      },
      {
        medicineId: 3,
        medicineName: '钙片',
        usageMethod: '口服，每日一次，每次两片',
        specification: '500mg*100片'
      }
    ]
  }
}

// 加载最近领用记录
const loadRecentRecords = async () => {
  recordsLoading.value = true
  try {
    const params = {
      page: recordsPagination.currentPage,
      size: recordsPagination.pageSize
    }

    const response = await getMedicineReceiveRecords(params)
    if (response.code === 200) {
      recentRecords.value = response.data.records || []
      recordsPagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取领用记录失败')
      // 模拟数据
      recentRecords.value = [
        {
          receiveId: 1,
          elderName: '张大爷',
          medicineName: '降压药',
          dosageUsed: '口服，每日一次，每次一片',
          receiveTime: '2024-10-03 08:00:00',
          notes: '按时服药',
          status: 'completed'
        },
        {
          receiveId: 2,
          elderName: '李大妈',
          medicineName: '降糖药',
          dosageUsed: '口服，每日两次，每次一片',
          receiveTime: '2024-10-03 08:15:00',
          notes: '餐后服用',
          status: 'completed'
        },
        {
          receiveId: 3,
          elderName: '王爷爷',
          medicineName: '钙片',
          dosageUsed: '口服，每日一次，每次两片',
          receiveTime: '2024-10-03 09:00:00',
          notes: '补充钙质',
          status: 'completed'
        }
      ]
      recordsPagination.total = recentRecords.value.length
    }
  } catch (error) {
    console.error('获取领用记录失败:', error)
    // 模拟数据
    recentRecords.value = [
      {
        receiveId: 1,
        elderName: '张大爷',
        medicineName: '降压药',
        dosageUsed: '口服，每日一次，每次一片',
        receiveTime: '2024-10-03 08:00:00',
        notes: '按时服药',
        status: 'completed'
      },
      {
        receiveId: 2,
        elderName: '李大妈',
        medicineName: '降糖药',
        dosageUsed: '口服，每日两次，每次一片',
        receiveTime: '2024-10-03 08:15:00',
        notes: '餐后服用',
        status: 'completed'
      }
    ]
    recordsPagination.total = recentRecords.value.length
  } finally {
    recordsLoading.value = false
  }
}

// 分页大小改变
const handleRecordsSizeChange = (size) => {
  recordsPagination.pageSize = size
  recordsPagination.currentPage = 1
  loadRecentRecords()
}

// 当前页改变
const handleRecordsCurrentChange = (page) => {
  recordsPagination.currentPage = page
  loadRecentRecords()
}

// 初始化加载
onMounted(() => {
  loadElderList()
  loadMedicineList()
  loadRecentRecords()
})
</script>

<style scoped>
.caregiver-medicine-receive-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.header {
  margin-bottom: 20px;
  text-align: center;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.header p {
  margin: 8px 0 0;
  color: #909399;
  font-size: 14px;
}

.form-section {
  margin-bottom: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recent-records-section {
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-card__header) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}
</style>
